package tool;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import javax.imageio.ImageIO;

import com.base.dao.ImageDao;
import com.base.dao._BaseDao;


/**
 * 单例模式
 * 整合图片下载 打水印 用于后补（解决当时没有及时下载下来图片的情况）
 * @author Administrator
 *
 */
public class ImageToolTwo {

	static String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
	
	private ImageDao id;
	
	// 单例模式 start
	private volatile static ImageToolTwo instance = null;
	private ImageToolTwo() {
		id=(ImageDao) _BaseDao.ac.getBean("ImageDao");
	}
	public static ImageToolTwo getInstance() {
		if (instance == null) {
			synchronized (ImageToolTwo.class) {// 1
				if (instance == null) {// 2
					instance = new ImageToolTwo();// 3
				}
			}
		}
		return instance;
	}
	
	
	
	/**
	 * @param urlString 下载地址 
	 * @param minkb 最小多少KB
	 * 
	 */
	@SuppressWarnings("finally")
	public static boolean testDownload(String urlString,int minkb) throws Exception {

		int fileSize=0;
		
		InputStream is=null;
		try{ 
		// 构造URL
		URL url = new URL(urlString);
	    // 打开连接
	    URLConnection con = url.openConnection();
	    //设置请求超时为5s
	    con.setConnectTimeout(5*1000);
	    // 输入流
	    is = con.getInputStream();
	
	    // 1K的数据缓冲
	    byte[] bs = new byte[1024];
	    // 读取到的数据长度
	    int len;
	    // 输出的文件流  
	    
	  
	    // 开始读取
	    while ((len = is.read(bs)) != -1) {
	      fileSize=fileSize+len;
	    }
	    
	   }finally{
	    // 完毕，关闭所有链接
	    if(is!=null)
		    is.close();
	    if(fileSize/1024>minkb)	//文件必须minkb以上
	    	return true;
	    else
	    	return false;
	    
	   }
	} 
	
	
	/**
	 * 给图片打水印
	 * @param srcImgPath	源文件路径（包含文件名）
	 * @param outImgPath	输出路径（包含文件名）
	 * @param markContentColor	水印颜色
	 * @param waterMarkContent	水印文字（内容）
	 * @param timeStr	水印文字（时间）
	 */
	public  void mark(String srcImgPath, String outImgPath, Color markContentColor, String waterMarkContent,String timeStr) {
		try {
            // 读取原图片信息
            File srcImgFile = new File(srcImgPath);
            Image srcImg = ImageIO.read(srcImgFile);
            int srcImgWidth = srcImg.getWidth(null);
            int srcImgHeight = srcImg.getHeight(null);
            // 加水印
            BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bufImg.createGraphics();
            g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
            //Font font = new Font("Courier New", Font.PLAIN, 12);
            Font font = new Font("宋体", Font.PLAIN, 30);  
            g.setColor(markContentColor); //根据图片的背景设置水印颜色
            
            g.setFont(font);
            int x1 = srcImgWidth - getWatermarkLength(waterMarkContent, g) - 30;
            int x2 = srcImgWidth - getWatermarkLength(timeStr, g) - 30;
            int y1 = srcImgHeight - 60;
            int y2 = srcImgHeight - 30;
            //int x = (srcImgWidth - getWatermarkLength(watermarkStr, g)) / 2;
            //int y = srcImgHeight / 2;
            g.drawString(waterMarkContent, x1, y1);
            g.drawString(timeStr, x2, y2);
            g.dispose();
            // 输出图片
            FileOutputStream outImgStream = new FileOutputStream(outImgPath);
            
            
            
            ImageIO.write(bufImg, "jpg", outImgStream);
            outImgStream.flush();
            outImgStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
	
	
	public  void mark(String localPath,String outImgPath,com.base.bean.Image img) throws IOException {
		
		FileOutputStream outImgStream=null;
		File srcImgFile=null;
		Image srcImg=null;
		try {
            // 读取原图片信息
           srcImgFile = new File(localPath+img.getMediaId()+".jpg");
            
            System.out.println(localPath+img.getMediaId()+".jpg");
            
            srcImg = ImageIO.read(srcImgFile);
            }catch(Exception e){
            	return;
            }
          try{
            int srcImgWidth = srcImg.getWidth(null);
            int srcImgHeight = srcImg.getHeight(null);
            // 加水印
            BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bufImg.createGraphics();
            g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
            //Font font = new Font("Courier New", Font.PLAIN, 12);
            Font font = new Font("宋体", Font.PLAIN, 30);  
            g.setColor(Color.blue); //根据图片的背景设置水印颜色
            
            
            //String timeStr=TimeTool.getNowTime()+"  "+TimeTool.getWeekDay();
    		long t=img.getCreated().getTime();
    		DateUtil du=new DateUtil();
    		du.setTime(t);
    		String r=du.getDateString();
    		String time=du.getTimeString();
    		int i=du.getWeek();
    		String xq=this.weekDays[i-1];
    		
    		String timeStr=r+" "+time+" "+xq;
            
            
            System.out.println(timeStr);
            
            
            
            g.setFont(font);
            int x1 = srcImgWidth - getWatermarkLength(img.getDiscription(), g) - 30;
            int x2 = srcImgWidth - getWatermarkLength(timeStr, g) - 30;
            int y1 = srcImgHeight - 60;
            int y2 = srcImgHeight - 30;
            //int x = (srcImgWidth - getWatermarkLength(watermarkStr, g)) / 2;
            //int y = srcImgHeight / 2;
            g.drawString(img.getDiscription(), x1, y1);
            g.drawString(timeStr, x2, y2);
            g.dispose();
            // 输出图片
            
//           Integer uid=img.getCreator();
//           System.out.println(img.getCreated());
            
            
            outImgStream = new FileOutputStream(outImgPath+"\\"+img.getFileName());
            
            
            
            ImageIO.write(bufImg, "jpg", outImgStream);
            
            System.out.println("##########:"+img.getMediaId());
            img.setState(3);
        } catch (Exception e) {
        	System.out.println("can't find:"+img.getMediaId());
        	img.setState(4);
        	id.merge(img);
            e.printStackTrace();
        }finally{
        	//outImgStream.flush();
            outImgStream.close();
            id.merge(img);
           
        }
	}
	
	
	
	/**
	 * 获取水印文字总长度
	 * @param waterMarkContent 水印的文字
	 * @param g
	 * @return 水印文字总长度
	 */
    private int getWatermarkLength(String waterMarkContent, Graphics2D g) {
        return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
    }
	
	
    
    public void downloadExceptionImg(int offset,int pageSize,String from,String to) throws IOException{
    	List<com.base.bean.Image> list=id.findByPage("from Image a where a.state=2 order by a.created", offset, pageSize);
		ImageToolTwo it=new ImageToolTwo();
		
		for(com.base.bean.Image img:list){
//			it.mark("E:\\hifo_img\\from", "E:\\hifo_img\\to", img);
			it.mark(from, to, img);
		}
    	
    }
    
    
	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
//		// TODO Auto-generated method stub
//		ImageDao id=(ImageDao) _BaseDao.ac.getBean("ImageDao");
//		List<com.base.bean.Image> list=id.findByPage("from Image a order by a.created", 0, 10);
//		ImageToolTwo it=new ImageToolTwo();
//		
//		for(com.base.bean.Image img:list){
//			it.mark("E:\\hifo_img\\from", "E:\\hifo_img\\to", img);
//		}
		
		ImageToolTwo it=new ImageToolTwo();
		
		for(int i=0;i<30;i++){
			try{
			it.downloadExceptionImg(i*100, 100, "E:\\hifo_img\\from\\", "E:\\hifo_img\\to\\");
			}catch(Exception e){
				continue;
			}
		}
		

	}

}
